package cn.itsource.ymcc.filter;


import cn.itsource.ymcc.config.ExcludeProperties;
import cn.itsource.ymcc.jwt.JwtUtils;
import cn.itsource.ymcc.jwt.Payload;
import cn.itsource.ymcc.jwt.PayloadData;
import cn.itsource.ymcc.jwt.RsaUtils;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;
import java.util.List;

/**
 * 认证拦截器
 *
 */
@Component
@Slf4j
public class AuthorizationFilter implements GlobalFilter, Ordered {
    @Value("${jwt.rsa.pub}")
    private String pub;
    @Autowired
    private ExcludeProperties excludeProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //响应对象
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer buffer = null;
        try {
            //放行登录请求
            if(excludeProperties.isExcluded(exchange.getRequest().getPath().value())){
                return chain.filter(exchange);
            }
            //获得请求头中的token
            List<String> headers = exchange.getRequest().getHeaders().get("U-TOKEN");

            log.info("检查 TOKEN = {}" ,headers);
            if(headers != null || !headers.isEmpty()){
                String jwtToken = headers.get(0);
                //利用jwt工具 公钥解密
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pub).getFile());
                Payload<PayloadData> paylode = JwtUtils.getInfoFromToken(jwtToken, publicKey, PayloadData.class);
                if (paylode!=null && paylode.getUserInfo()!=null && paylode.getUserInfo().getLogininfo()!=null){
                    // 如果都不是空 说明已经登录 放行
                    return chain.filter(exchange);
                }
            }
            byte[] bytes = JSON.toJSONString(JsonResult.error("noLogin")).getBytes("utf-8");
            buffer = response.bufferFactory().wrap(bytes);
            //设置完成相应，不会继续执行后面的filter
            //response.setComplete();
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //把结果写给客户端
        return response.writeWith(Mono.just(buffer));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
